/*
 * axios全局配置
 */
import axios from 'axios'
import { message } from 'antd'
import { store } from '../store'
import qs from 'qs'
import { changeTokenAction, changeRefreshToken, changeMenuListLine, changeMenuList } from '@/store/reducers/login'
import { refreshToken, getUserInfo } from '@/api/index'
import { changeUserInfoAction } from '@/store/reducers/user'
// 是否正在刷新的标记
let isRefreshing = false
let requestErrorArr = [] as any
const instance = axios.create({
  timeout: 60000,
})
const removeLoginStatus = () => {
  message.warning('登录已过期，请重新登录')
  store.dispatch(changeTokenAction(''))
  store.dispatch(changeRefreshToken(''))
  store.dispatch(changeUserInfoAction({}))
  store.dispatch(changeMenuList([]))
  store.dispatch(changeMenuListLine([]))
  if (window.location.hash.indexOf('#') > -1) {
    window.location.hash = '/login'
  } else {
    window.location.replace('/login')
  }
}
//配置请求拦截器
instance.interceptors.request.use(
  (config) => {
    const token = store.getState().login.token
    if (token) {
      config.headers!.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  },
)

//配置响应拦截器
instance.interceptors.response.use(
  (response) => {
    if (response?.data?.code === 200) {
      return response?.data
    } else {
      message.error(response?.data?.msg || '系统异常')
      return Promise.reject(response?.data)
    }
  },
  async (error) => {
    if (error?.response?.status === 401) {
      if (!isRefreshing) {
        isRefreshing = true
        // 无感刷新token
        const refresh_token = store.getState().login.refresh_token
        if (!refresh_token) {
          removeLoginStatus()
          return
        }
        const res = await refreshToken({ refresh_token })
          .catch(() => removeLoginStatus())
          .finally(() => {
            isRefreshing = false
          })
        store.dispatch(changeTokenAction(res?.data?.access_token || ''))
        store.dispatch(changeRefreshToken(res?.data?.refresh_token || ''))
        const info = await getUserInfo({})
        store.dispatch(changeUserInfoAction(info.data.user_info))
        if (res.data.access_token) {
          requestErrorArr.forEach((cb: (token: string) => Promise<any>) => cb(res?.data?.access_token))
          requestErrorArr = []
          return instance(error.config)
        }
      } else {
        return new Promise((resolve) => {
          // 用函数形式将 resolve 存入，等待刷新后再执行
          requestErrorArr.push((token: string) => {
            error.response.headers.Authorization = `${token}`
            resolve(instance(error.config))
          })
        })
      }
    }
    return Promise.reject(error)
  },
)

export const getRequest = <T>(url = '', data = {}) => {
  if (qs.stringify(data)) {
    url += url.includes('?') ? '&' + qs.stringify(data) : '?' + qs.stringify(data)
  }
  return instance.get(url) as Promise<IResponse<T>>
}
export const postRequest = <T>(url = '', data = {}) => {
  return instance.post(url, data) as Promise<IResponsePost<T>>
}

export const postRequestOnlyData = <T>(url = '', data = {}) => {
  //过滤对象中值为''
  const filterData = Object.fromEntries(Object.entries(data).filter(([_, val]) => val !== ''))
  return instance.post(url, filterData) as Promise<IResponseOnlyData<T>>
}

export const postRequestJson = <T>(url = '', data: any) => {
  return instance.post(url, data, { headers: { 'Content-Type': 'application/json' } }) as Promise<IResponsePost<T>>
}
